package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired(required = false)
    private EmployeeService employeeService;

    @Autowired
    private HttpSession session;

    /**
     * 用户登录
     *
     * @param employee
     * @return
     */
    @RequestMapping("login")
    public R<Employee> login(@RequestBody Employee employee) {
        //1.调用业务层进行登录,获取返回结果
        R<Employee> login = employeeService.login(employee);

        //2.判断是否登录成功,成功写入session
        if (login.getCode() == 1) {
            session.setAttribute("employee", login.getData().getId());
        }
        //3.返回数据
        return login;
    }


    /**
     * 用户退出
     *
     * @param employee
     * @return
     */
    @RequestMapping("logout")
    public R<Employee> logout(Employee employee) {
        session.invalidate();
        return R.success(employee);
    }


    /**
     * 添加用户
     *
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Employee employee) {

        //1.获取登录数据中存储到的id
        Long id = (Long) session.getAttribute("employee");

        //2.完善数据
        //创建人
        employee.setCreateUser(id);

        //修改人
        employee.setUpdateUser(id);

        //调用业务
        employeeService.save(employee);

        return R.success("添加成功");
    }


    /**
     * 处理分页请求
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @RequestMapping("/page")
    public R<Page<Employee>> findByPage(Integer page, Integer pageSize, String name) {
        Page<Employee> byPage = employeeService.findByPage(page, pageSize, name);
        return R.success(byPage);
    }


    @PutMapping
    public R<String> update(@RequestBody Employee employee) {
        //1.获取当前操作人的id
        Long id = (Long) session.getAttribute("employee");

        //2.完善数据修改人
        employee.setUpdateUser(id);

        //3.调用业务修改
        employeeService.update(employee);

        //4.返回数据
        return R.success("修改成功");
    }



    @GetMapping("/{id}")
    public R<Employee> findById(@PathVariable Long id) {
        R<Employee> byId = employeeService.findById(id);
        return byId;
    }

}
